package com.xds.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.xds.common.exception.NoStockException;
import com.xds.common.to.OrderTo;
import com.xds.common.to.mq.StockDetailTo;
import com.xds.common.to.mq.StockLockedTo;
import com.xds.common.utils.R;

import com.xds.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.xds.gulimall.ware.entity.WareOrderTaskEntity;
import com.xds.gulimall.ware.feign.OrderFeign;
import com.xds.gulimall.ware.feign.ProductFeignService;
import com.xds.gulimall.ware.service.WareOrderTaskDetailService;
import com.xds.gulimall.ware.service.WareOrderTaskService;
import com.xds.gulimall.ware.vo.*;
import lombok.Data;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xds.common.utils.PageUtils;
import com.xds.common.utils.Query;

import com.xds.gulimall.ware.dao.WareSkuDao;
import com.xds.gulimall.ware.entity.WareSkuEntity;
import com.xds.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    WareSkuDao wareSkuDao;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    WareOrderTaskDetailService orderTaskDetailService;
    @Autowired
    WareOrderTaskService orderTaskService;
    @Autowired
    OrderFeign orderFeign;
    Long Sid;

    /**
     * 释放下单成功 库存锁定，业务调用失败，导致订单失败回滚
     * @param
     * @return
     */

    private void unlockStock(Long skuId,Long wareId,Integer num,Long taskDetailId,Long sId){
        WareSkuEntity wareSkuEntity = wareSkuDao.selectById(sId);
        wareSkuEntity.setStockLocked(wareSkuEntity.getStockLocked()-num);
        wareSkuDao.updateById(wareSkuEntity);
        //更新库存工作单
        WareOrderTaskDetailEntity orderTaskDetail = new WareOrderTaskDetailEntity();
        orderTaskDetail.setId(taskDetailId);
        orderTaskDetail.setLockStatus(2);
        orderTaskDetailService.updateById(orderTaskDetail);
    }
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         * skuId:
         * wareId:
         */
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)){
            wrapper.eq("sku_id",skuId);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)){
            wrapper.eq("ware_id",wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),wrapper

        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1.判断如果没有库存记录 新增操作
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (entities.size()==0||entities==null){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字
            R info = productFeignService.info(skuId);
            Map<String,Object> spuInfo = (Map<String, Object>) info.get("spuInfo");
            try {
                if (info.getCode()==0){
                    wareSkuEntity.setSkuName((String) spuInfo.get("skuName"));
                }
            }catch (Exception e){

            }
           wareSkuDao.insert(wareSkuEntity);
        }else {
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStocke(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            //查询当前sku的总库存亮
          Long   count=   baseMapper.getSkuStock(skuId);
          vo.setSkuId(skuId);
          vo.setHasStock(count==null?false:count>0);
            return vo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 为某个订单锁定库存
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public Boolean orderLockStock(WareSkuLockVo vo) {
        /**
         * 保存库存工作单的详情
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        orderTaskService.save(taskEntity);
        List<OrderConfirmVo.OderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            //查询这个商品在哪里有库存
            QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("sku_id",skuId);
            List<WareSkuEntity> wareSkuEntities = baseMapper.selectList(wrapper);
            List<Long> wareId = wareSkuEntities.stream().filter(f->(f.getStock()-f.getStockLocked())>0).map(ware -> ware.getWareId()
            ).collect(Collectors.toList());
            stock.setWareId(wareId);
            //锁定库存
            return stock;
        }).collect(Collectors.toList());
        for (SkuWareHasStock stock : collect) {
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareId();
            if (wareIds==null||wareIds.size()==0){
                throw  new NoStockException(skuId);
            }
            int flag=0;
            int bflag=0;
            for (Long wareId : wareIds) {
                if (wareIds.size()==2&&wareIds.get(0) == wareIds.get(1)) {
                    List<WareSkuEntity> wareSkuEntitie = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId)
                            .eq("ware_id", wareIds.get(0)));
                    if (flag==0) {
                        WareSkuEntity wareSkuEntity = wareSkuEntitie.get(0);
                        wareSkuEntity.setStockLocked(wareSkuEntity.getStockLocked() + stock.getNum());
                        if (wareSkuEntity.getStock()-wareSkuEntity.getStockLocked()>= stock.getNum()) {
                            wareSkuDao.updateById(wareSkuEntity);
                            //TODO 告诉MQ库存锁定成功
                                WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity(null,skuId,"",stock.getNum(),taskEntity.getId(),wareId,1);
                                orderTaskDetailService.save(detailEntity);
                            StockLockedTo lockedTo = new StockLockedTo();
                            lockedTo.setId(taskEntity.getId());
                            StockDetailTo stockDetailTo = new StockDetailTo();
                            BeanUtils.copyProperties(detailEntity,stockDetailTo);
                            lockedTo.setDetailTo(stockDetailTo);
                            lockedTo.setSId(wareSkuEntity.getId());
                            Sid=wareSkuEntity.getId();
                            rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",lockedTo);
                            flag = flag + 1;
                        }else {
                            WareSkuEntity wareSkuEntity2 = wareSkuEntitie.get(1);
                            wareSkuEntity2.setStockLocked(wareSkuEntity2.getStockLocked() + stock.getNum());
                            if (wareSkuEntity2.getStock()-wareSkuEntity2.getStockLocked()>= stock.getNum()) {
                                wareSkuDao.updateById(wareSkuEntity2);
                                //TODO 告诉MQ库存锁定成功
                                WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity(null,skuId,"",stock.getNum(),taskEntity.getId(),wareId,1);
                                orderTaskDetailService.save(detailEntity);
                                StockLockedTo lockedTo = new StockLockedTo();
                                lockedTo.setId(taskEntity.getId());
                                StockDetailTo stockDetailTo = new StockDetailTo();
                                BeanUtils.copyProperties(detailEntity,stockDetailTo);
                                lockedTo.setDetailTo(stockDetailTo);
                                lockedTo.setSId(wareSkuEntity2.getId());
                                Sid=wareSkuEntity.getId();
                                rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",lockedTo);
                                flag = flag + 1;
                            }
                        }
                    }
                } else {
                    if (bflag == 0) {
                        WareSkuEntity wareSkuEntity = wareSkuDao.selectOne(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
                        wareSkuEntity.setStockLocked(wareSkuEntity.getStockLocked() + stock.getNum());
                        if (wareSkuEntity.getStock()-wareSkuEntity.getStockLocked()>=stock.getNum()) {
                            wareSkuDao.updateById(wareSkuEntity);
                            //TODO 告诉MQ库存锁定成功
                            WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity(null,skuId,"",stock.getNum(),taskEntity.getId(),wareId,1);
                            orderTaskDetailService.save(detailEntity);
                            StockLockedTo lockedTo = new StockLockedTo();
                            lockedTo.setId(taskEntity.getId());
                            StockDetailTo stockDetailTo = new StockDetailTo();
                            BeanUtils.copyProperties(detailEntity,stockDetailTo);
                            lockedTo.setDetailTo(stockDetailTo);
                            lockedTo.setSId(wareSkuEntity.getId());
                            Sid=wareSkuEntity.getId();
                            rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",lockedTo);
                            bflag = bflag + 1;
                        }
                    }
                }
            }
            if (flag==0&&bflag==0){
                //锁库存失败
                throw  new NoStockException(skuId);
            }

        }
        //锁定成功
        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {
            StockDetailTo detailTo = to.getDetailTo();
            Long detailId = detailTo.getId();
            WareOrderTaskDetailEntity entity = orderTaskDetailService.getById(detailId);
            if (entity!=null){
                //解锁
                Long id = to.getId();//库存工作单id
                WareOrderTaskEntity taskEntity = orderTaskService.getById(id);
                String orderSn = taskEntity.getOrderSn();
                R r = orderFeign.orderStatus(orderSn);
                if (r.getCode()==0){
                    //订单数据返回成功
                    OrderVo data = r.getData("data",new TypeReference<OrderVo>() {
                    });

                    if (data==null||data.getStatus()==4) {
                        //订单已经被取消了 解锁库存
                        //状态已锁定 1 未解锁
                        if (entity.getLockStatus() == 1) {
                            unlockStock(detailTo.getSkuId(), detailTo.getWareId(), detailTo.getSkuNum(), detailId, to.getSId());
                        }
                    }
                }else {
                    //消息拒绝重新发回队列 让别人消费解锁
                        throw  new RuntimeException("远程服务调用失败");
                }

            }else {
                //无需解锁
            }
        }

    /**
     * 防止订单服务卡死，导致订单状态消息一直改不了，库存消息优先到期，查订单新建状态，什么都做不了走了
     * @param orderTo
     */
    @Override
    @Transactional
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
//        R r = orderFeign.orderStatus(orderSn);
        WareOrderTaskEntity taskEntity = orderTaskService.getOne(new QueryWrapper<WareOrderTaskEntity>().eq("order_sn", orderSn));
        List<WareOrderTaskDetailEntity> detailEntityList = orderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", taskEntity.getId())
                .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity entity : detailEntityList) {
            unlockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId(),Sid);
        }
    }

    @Data
    class SkuWareHasStock{
        private Long skuId;
        private List<Long> wareId;
        private Integer num;
    }




}